/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-18 19:09:32
 * @Description  : 请求日志记录中间件
 */

const { SystemLog } = require('@/framework/mongoose/index')
const { LOG_TYPE } = require('@/constants/log')
const R = require('@/models/Response')
const { ERROR_SYSTEM_CODE } = require('@/constants/errorCode')

// 创建一个日志记录中间件
module.exports.httploggerMiddleware = () => {
  return async (ctx, next) => {
    // 请求前记录时间
    // 请求前记录一下用户的IP和UA
    const { method, url, ip } = ctx.request
    const startTime = new Date()
    ctx.mySession = {
      ip: ip,
      ua: ctx.request.header['user-agent']
    }
    await next()

    // 如果ctx.body为undefined，说明没有匹配到路由
    if (!ctx.body) {
      return R.error(ERROR_SYSTEM_CODE.ROUTER_NOT_MATCH_ERROR)
    }

    console.log(ctx.user)

    const endTime = new Date()

    let requestParams
    if (method.toLowerCase() === 'get') {
      requestParams = ctx.query
    } else {
      requestParams = ctx.request.body
    }
    const log = {
      requestTime: `${endTime - startTime}ms`,
      requestMethod: ctx.request.method,
      requestUrl: url,
      requestParams,
      responseBody: { code: ctx.body.code, message: ctx.body.message },
      responseCode: ctx.status,
      ip,
      ua: ctx.request.header['user-agent'],
      userId: ctx?.user?.id || '',
      username: ctx?.user?.username
    }

    try {
      const mylog = new SystemLog({
        ...log,
        type: LOG_TYPE.HTTP_LOG
      })
      await mylog.save()
    } catch {}

    // 请求如果出现业务错误码，http.fail记录
    if (+log.responseBody.code !== 0) {
      try {
        const failLog = new SystemLog({
          ...log,
          type: LOG_TYPE.HTTP_FAIL
        })
        failLog.save()
      } catch (error) {}
    }
  }
}
